// pages/biz/estateDetail/estateDetail.js
//引入请求接口文件
// --------秒杀---------2019.6.10更新
//   1，报名
// 2，支付报名费
// 3，等待活动开始
// 4，立即抢购
// 5，立即抢购（灰色按钮）
// 6，支付订金
// 7，已售空
// 8，活动已结束
// ------竞拍---------2019.6.10更新
//   1，报名
// 2，支付报名费
// 3，等待活动开始
// 4，叫价
// 5，支付订金
// 6，活动结束
// productType
// 1，2，3是属于房源类商品，4，5，6，7是属于普通商品吧
import Serv from './estateDetailServ';
var regeneratorRuntime = require("../../../../lib/js/runtime-module.js")
import util from '../../../../utils/util2'
import Config from '../../../../utils/config.js'
var WxParse = require('../../../../wxParse/wxParse.js');
let propertyType = {
  11: "住宅", 12: "公寓", 21: "地上停车位", 22: "地下停车位（非人防）", 23: "地下停车位（人防）", 24: '地下车库',
  25: '地上车库', 31: "地上商铺", 32: "地下商铺",33: '地上集中商业',
  34: '地下集中商业',
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrls: [],
    mBox: false,
    changepx: "160rpx",
    countDownList: [],
    actEndTimeList: [],
    like:true,
    estateDetail:{},
    goodsList:[],
    current:1,
    disable:false,
    show:false,
    opacity: 'rgba(255,255,255,0)',
    productDeType: [4, 5, 6, 7],
    productHouseType: [1, 2, 3]
  },
  swiperChange(e) {
    this.setData({ current: e.detail.current + 1 })
  },
  // 请求详情
  async getqueryDetail(parmas,cbk){
    let { data, success,msg}= await Serv.getqueryDetail(parmas)
    if(success){
      data.propertyType = propertyType[data.propertyType]
      if (data.squarePrice){
        data.squarePrice = Math.round(data.squarePrice)
      }
      this.setData({
        estateDetail: data,
        tips: `提示：活动将在${util.dateChina(data.startTime)}开始！`,
        imgUrls: data.imageUrls
      })  
      WxParse.wxParse('content', 'html', data.productDesc, this, 0)
      // debugger
      if (data.isStartActivity == 3){
        wx.showToast({
          title: '活动已结束',
          icon:'none'
        })
      }
        //请求回来todo
        // -------倒计时-----------
        let goodsList = [{ actEndTime: data.isStartActivity == 1 ? data.startTime : data.endTime }]
        let endTimeList = [];
        console.log(goodsList)
        // 将活动的结束时间参数提成一个单独的数组，方便操作
        goodsList.forEach(o => { endTimeList.push(o.actEndTime) })
        this.setData({ actEndTimeList: endTimeList, follow: data.follow });
        wx.setStorageSync('currentDetail', data)
        console.log()

    }else{
      wx.showToast({
        title: msg,
        icon:'none'
      })
    }
    
  },
  //确定绑定钱包
  confirmwallet() {
    wx.redirectTo({
      url: `/subPackages2/pages/wallet/openWallet/openWallet`,
    });
  },
  cancelwallet() {
    console.log(111)
    this.setData({
      show: false,
    })
  },
  //判断是否绑定钱包
  async flagMoney(e) {
    let { data, success } = await Serv.flagMoney({accountId:wx.getStorageSync('userId')})
    let { estateDetail } = this.data
    let { url } = e.currentTarget.dataset
    if (success) {
      if (data) {
        wx.navigateTo({
          url
        })
      } else {
        this.setData({
          show: true
        })
      }
    }
  },
  //点击关注
  async attention(e) {
    console.log(e)
    let { estateDetail,follow } = this.data
    console.log(follow)
    
    let { data, success } = await Serv.favoriteCreate({ seckillProductId: estateDetail.seckillProductId, type: 3,follow:follow==0?1:0})
    if(success){
      if (follow == 0) {
        follow = 1
      } else {
        follow = 0
      }
      this.setData({
        follow
      })
    }
    
  },
  toMap() {
    let { estateDetail} = this.data
    wx.openLocation({
      latitude: Number(estateDetail.latitude),
      longitude: Number(estateDetail.longitude),
      name: estateDetail.address
    })
  },
  //routerGo
  routerGo(e) {
    let url = e.currentTarget.dataset.url
    wx.navigateTo({
      url,
    })
  },
  goTo(e){
    wx.navigateTo({
      url: `../../findHouse/estateAllDetail/estateAllDetail?productId=${e.currentTarget.dataset.id}&type=${e.currentTarget.dataset.type}`,
    })
  },
  showBox: function () {
    this.setData({ mBox: !this.data.mBox })
  },
  //-加载当前秒杀围观人数
  async queryCurrentDetail(parmas, cbk) {
    let { data } = await Serv.queryCurrentDetail(parmas)
    this.setData({
      //maxPrice: data.price,
      attrList: data.avatars,
      userCount: data.userCount,
      stock:data.stock
    })
    cbk && cbk(data)
  },
  noSubmit(){
    if (wx.getStorageSync(Config.userIdKey).length > 0){
      wx.showToast({
        title: '您没有资格参加此次秒杀',
        icon: 'none',
      })
    }else{
      wx.navigateTo({
        url: '/pages/biz/login/login',
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onLoad(opt) {
    console.log(opt)
    this.queryCurrentDetail({ productId: opt.pid, seckillProductId: opt.id, sellType: 1 })
    //将计时器赋值给setInter
    this.data.setInter = setInterval(() => {
      this.queryCurrentDetail({ productId: opt.pid, seckillProductId: opt.id, sellType: 1 })
    }, 10000) 
    //发请求
    this.getqueryDetail(opt.id)
    
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    // console.log(this.data.actEndTimeList)
    let endTimeList = this.data.actEndTimeList;
    let countDownArr = [];
    let { estateDetail } = this.data
    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(o => {
      let endTime = util.dateFromString(o).getTime();
      let obj = null;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600) + (24 * day);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: this.timeFormat(day),
          hou: this.timeFormat(hou),
          min: this.timeFormat(min),
          sec: this.timeFormat(sec)
        }
      } else {//活动已结束，全部设置为'00'
        obj = {
          day: '00',
          hou: '00',
          min: '00',
          sec: '00'
        }
        // console.log('----')
        if (estateDetail.isStartActivity == 1){
          estateDetail.isStartActivity = 2
          this.setData({
            estateDetail,
            actEndTimeList: [estateDetail.endTime]
          })
        } else if (estateDetail.isStartActivity == 2){
          estateDetail.isStartActivity = 3
          this.setData({
            disable:true,
            estateDetail,
          })
        }
        
      }
      countDownArr.push(obj);
    })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ countDownList: countDownArr })
    this.data.timer = setTimeout(this.countDown, 1000);
  },
  phone: function (e) {
    let { mobile } = this.data.estateDetail
    wx.makePhoneCall({ phoneNumber: mobile })
  },
  onShow:function(){
    // 执行倒计时函数
    this.countDown();
  },
  onUnload: function () {

    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
    clearTimeout(this.data.timer)
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log(this.data.timer)
    var that = this;
    //清除计时器  即清除setInter
    clearInterval(that.data.setInter)
    clearTimeout(this.data.timer)
  },
  // 报名
  loadImage(e){
    console.log(e)
    this.setData({
      height:e.detail.height
    })
  },
  enroll:function(e){
    let activityType = e.currentTarget.dataset.activitytype
    let { seckillProductId } = this.data.estateDetail
    this.getEnroll({ activityType, seckillProductId})
  },
  async getEnroll(parmas){
    let{data,msg,success} = await Serv.enroll(parmas)
    let estateDetail = this.data.estateDetail
    if(success){
      this.setData({
        tips: `提示：活动将在${util.dateChina(estateDetail.startTime)}开始！`,
        flagEnroll: data
      }, () => {
        if (data) {
          this.showDialog()
        } else {
          let { estateDetail } = this.data
          let url = `/subPackages2/pages/pay/payment/payment?actionType=1&seckillProductId=${estateDetail.seckillProductId}`
          this.getqueryDetail(estateDetail.seckillProductId)
          wx.navigateTo({
            url: url,
          })
        }
      })
    }else{
      wx.showToast({
        title: msg,
        icon:'none'
      })
    }
    
  },
  onReady: function () {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
    //this.showDialog()
  },
  showDialog() {
    this.dialog.showDialog();
  },
  hide() {
    this.dialog.hideDialog();
  },
  //取消事件
  _onCancel() {
    console.log('你点击了取消');
    let {estateDetail} = this.data
    this.dialog.hideDialog();
    this.getqueryDetail(estateDetail.seckillProductId)
  },
  //确认事件
  _onOk() {
    console.log('你点击了确定');
    this.dialog.hideDialog();
    let {estateDetail} = this.data
    let url = `/subPackages2/pages/pay/payment/payment?actionType=1&seckillProductId=${estateDetail.seckillProductId}`
    this.getqueryDetail(estateDetail.seckillProductId)
    wx.navigateTo({
      url: url,
    })
    
  },
})